package test.jgroups;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;

import org.jgroups.Address;
import org.jgroups.util.UUID;
import org.jgroups.util.Util;

public class MemberIdentity implements Address, Comparable<Address> {
	private UUID uuid;
	private String name;
	private String ip;

	public MemberIdentity(UUID uuid, String name, String ip) {
		this.uuid = uuid;
		this.name = name;
		this.ip = ip;
	}

	public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
		uuid.readExternal(in);
		name = in.readUTF();
		ip = in.readUTF();
	}

	public void writeExternal(ObjectOutput out) throws IOException {
		uuid.writeExternal(out);
		out.writeUTF(name);
		out.writeUTF(ip);
	}

	public void readFrom(DataInput in) throws Exception {
		uuid.readFrom(in);
		name = Util.readString(in);
		ip = Util.readString(in);
	}

	public void writeTo(DataOutput out) throws Exception {
		uuid.writeTo(out);
		Util.writeString(name, out);
		Util.writeString(ip, out);
	}

	public int size() {
		return uuid.size() + Util.size(name) + Util.size(ip);
	}

	@Override
	public int compareTo(Address other) {
		if (other instanceof MemberIdentity) {
			return ((MemberIdentity) other).uuid.compareTo(uuid);
		} else if (other instanceof UUID) {
			return other.compareTo(this.uuid);
		} else
			throw new IllegalArgumentException("must copmpare to MemberIdentity or org.jgroups.util.UUID");
	}

	@Override
	public String toString() {
		return "MemberIdentity [uuid=" + uuid + ", name=" + name + ", ip=" + ip + "]";
	}
}
